﻿import 'dart:developer' as developer;
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/common/utils/toast_util.dart';
import '../../../core/controllers/ring_controller.dart';
import '../../../core/repository/default_api.dart';
import '../../../services/device_sn_manager.dart';
import '../../../core/models/heart_rate_api_data.dart';
import '../calendar/simple_calendar_view.dart';

/// 时间范围枚举
enum TimeRange {
  day,
  week,
  month,
}

/// 心率变异性数据模型
class HeartRateVariabilityData {
  final DateTime date;
  final int hrvValue;
  final int? sleepHrv;
  final int? awakeHrv;
  final List<int> hourlyData;
  final Map<String, int> zoneData;

  HeartRateVariabilityData({
    required this.date,
    required this.hrvValue,
    this.sleepHrv,
    this.awakeHrv,
    required this.hourlyData,
    required this.zoneData,
  });
}

/// 心率变异性页面控制器
class HeartRateVariabilityLogic extends GetxController {
  /// 戒指控制器
  late RingController _ringController;

  /// 获取戒指控制器
  RingController get ringController => _ringController;

  /// 当前时间范围
  final Rx<TimeRange> currentTimeRange = TimeRange.day.obs;

  /// 选中的时间索引
  final RxInt selectedTimeIndex = (-1).obs;

  /// 是否正在加载详细数据
  final RxBool isLoadingDetailedData = false.obs;

  /// 详细心率变异性数据
  final RxList<int> detailedHrvData = <int>[].obs;

  /// 拖动线位置
  final RxDouble dragLineX = 0.0.obs;

  /// 模拟心率变异性数据
  final Rx<HeartRateVariabilityData?> hrvData =
      Rx<HeartRateVariabilityData?>(null);

  /// API HRV平均值数据
  final Rxn<HrvAverageData> hrvAverageData = Rxn<HrvAverageData>();

  @override
  void onInit() {
    super.onInit();
    _ringController = Get.find<RingController>();
    _loadHrvData();
    // 延迟调用二级页接口
    Future.delayed(const Duration(milliseconds: 100), () {
      _fetchHrvSecondaryData();
    });
  }

  /// 设置时间范围
  void setTimeRange(TimeRange timeRange) {
    currentTimeRange.value = timeRange;
    selectedTimeIndex.value = -1;
    _loadHrvData();
    // 切换时间范围时重新获取数据
    _fetchHrvSecondaryData();
  }

  /// 加载心率变异性数据
  void _loadHrvData() {
    // 模拟心率变异性数据
    final now = DateTime.now();
    final hourlyData = List.generate(48, (index) {
      // 模拟24小时的心率变异性数据，每30分钟一个数据点
      final hour = index * 0.5;
      if (hour >= 22 || hour <= 6) {
        // 睡眠时间，心率变异性较高
        return 45 + (index % 15);
      } else if (hour >= 7 && hour <= 9) {
        // 早晨，心率变异性中等
        return 35 + (index % 10);
      } else if (hour >= 12 && hour <= 14) {
        // 中午，心率变异性较低
        return 25 + (index % 8);
      } else if (hour >= 18 && hour <= 20) {
        // 傍晚，心率变异性中等
        return 30 + (index % 12);
      } else {
        // 其他时间
        return 40 + (index % 10);
      }
    });

    final zoneData = {
      '优秀': 180, // 分钟
      '良好': 120,
      '一般': 60,
      '较差': 30,
      '很差': 10,
    };

    hrvData.value = HeartRateVariabilityData(
      date: now,
      hrvValue: 51, // 平均心率变异性
      sleepHrv: 58,
      awakeHrv: 45,
      hourlyData: hourlyData,
      zoneData: zoneData,
    );

    // 加载详细数据
    if (currentTimeRange.value == TimeRange.day) {
      detailedHrvData.value = hourlyData;
    }
  }

  /// 显示日历选择器
  void showCalendarPicker() async {
    final selectedDate = await Get.to(() => const SimpleCalendarView(
      calendarType: CalendarType.hrv,
    ));
    if (selectedDate != null && selectedDate is String) {
      loadDataByDate(selectedDate);
    }
  }

  /// 处理图表拖动更新
  void handleChartPanUpdate(double dx, double barWidth, int dataLength) {
    final index = (dx / barWidth).floor();
    if (index >= 0 && index < dataLength) {
      selectedTimeIndex.value = index;
      dragLineX.value = dx;
    }
  }

  /// 处理图表拖动结束
  void handleChartPanEnd() {
    dragLineX.value = 0.0;
  }

  /// 处理图表点击
  void handleChartTapUp(double dx, double barWidth, int dataLength) {
    final index = (dx / barWidth).floor();
    if (index >= 0 && index < dataLength) {
      selectedTimeIndex.value = index;
    }
  }

  /// 获取总时长
  String getTotalDuration() {
    final data = hrvData.value;
    if (data == null) return '-- 小时 -- 分钟';

    final totalMinutes =
        data.zoneData.values.fold<int>(0, (sum, minutes) => sum + minutes);
    final hours = totalMinutes ~/ 60;
    final minutes = totalMinutes % 60;

    return '$hours 小时 $minutes 分钟';
  }

  /// 获取HRV状态描述
  String getHrvStatus(int hrvValue) {
    if (hrvValue >= 50) return '优秀';
    if (hrvValue >= 40) return '良好';
    if (hrvValue >= 30) return '一般';
    if (hrvValue >= 20) return '较差';
    return '很差';
  }

  /// 获取HRV状态颜色
  Color getHrvStatusColor(int hrvValue) {
    if (hrvValue >= 50) return Colors.green;
    if (hrvValue >= 40) return Colors.blue;
    if (hrvValue >= 30) return Colors.orange;
    if (hrvValue >= 20) return Colors.red;
    return Colors.red[900]!;
  }

  /// 获取心率变异性二级页数据
  Future<void> _fetchHrvSecondaryData() async {
    try {
      developer.log('📊 开始获取心率变异性二级页数据...', name: 'HRVController');

      // 获取设备序列号
      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();
      if (deviceSn.isEmpty) {
        developer.log('❌ 设备SN为空，无法获取HRV数据', name: 'HRVController');
        return;
      }

      // 获取当前日期
      final now = DateTime.now();
      final recordDate =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      developer.log('📅 设备序列号: $deviceSn, 日期: $recordDate',
          name: 'HRVController');

      // 调用心率变异性平均值接口
      await _fetchHrvAverage(deviceSn, recordDate);

      developer.log('✅ 心率变异性二级页数据获取完成', name: 'HRVController');
    } catch (e) {
      developer.log('❌ 获取心率变异性二级页数据异常: $e', name: 'HRVController');
    }
  }

  /// 获取当前时间范围对应的type值
  String _getTypeFromTimeRange() {
    switch (currentTimeRange.value) {
      case TimeRange.day:
        return '1';
      case TimeRange.week:
        return '2';
      case TimeRange.month:
        return '3';
    }
  }

  /// 获取心率变异性平均值
  Future<void> _fetchHrvAverage(String deviceSn, String recordDate) async {
    try {
      final response = await DefaultApi().queryHrvAverageGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      developer.log('✅ 心率变异性平均值获取成功: $response', name: 'HRVController');

      // 解析数据
      if (response != null && response['data'] != null) {
        hrvAverageData.value = HrvAverageData.fromJson(response['data']);
        developer.log('✅ 心率变异性平均值数据解析成功', name: 'HRVController');
      }
    } catch (e) {
      developer.log('❌ 获取心率变异性平均值失败: $e', name: 'HRVController');
    }
  }

  /// 获取心率变异性统计-手动测量记录
  Future<void> fetchHrvInfo() async {
    try {
      developer.log('📊 开始获取心率变异性统计数据...', name: 'HRVController');

      // 获取设备序列号
      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();
      if (deviceSn.isEmpty) {
        developer.log('❌ 设备SN为空，无法获取HRV统计数据', name: 'HRVController');
        Toast.show('设备未连接');
        return;
      }

      // 获取当前日期
      final now = DateTime.now();
      final recordDate =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      developer.log('📅 设备序列号: $deviceSn, 日期: $recordDate',
          name: 'HRVController');

      // 调用心率变异性统计接口
      final response = await DefaultApi().queryHrvInfoGet(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: true,
        isShowLoading: true,
      );

      developer.log('✅ 心率变异性统计数据获取成功: $response', name: 'HRVController');

      // 这里可以处理返回的数据，更新UI
      // 例如：跳转到统计页面或显示数据
    } catch (e) {
      developer.log('❌ 获取心率变异性统计数据失败: $e', name: 'HRVController');
      Toast.show('获取数据失败');
    }
  }

  /// 获取日期标题（根据时间范围使用不同字段）
  String getDateTitle() {
    final apiData = hrvAverageData.value;
    
    if (apiData != null) {
      // 周和月视图使用 dateStart 和 dateEnd
      if (currentTimeRange.value == TimeRange.week ||
          currentTimeRange.value == TimeRange.month) {
        if (apiData.dateStart != null && apiData.dateEnd != null) {
          return '${apiData.dateStart} - ${apiData.dateEnd}';
        }
      }
      
      // 日视图使用 recordDate 和 weekName
      if (currentTimeRange.value == TimeRange.day &&
          apiData.recordDate.isNotEmpty) {
        final endTime = apiData.endTime ?? '00:00';
        return '${apiData.recordDate}，${apiData.weekName}，$endTime 平均';
      }
    }

    // 降级方案：使用当前日期
    final d = DateTime.now();
    const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    final weekday = weekdays[(d.weekday - 1).clamp(0, 6)];
    return '${d.year}年${d.month.toString().padLeft(2, '0')}月${d.day.toString().padLeft(2, '0')}日，$weekday，00:00 平均';
  }

  /// 根据指定日期加载数据
  void loadDataByDate(String recordDate) {
    developer.log('📅 根据日期加载心率变异性数据: $recordDate', name: 'HRVController');
    
    // 获取设备SN
    final deviceSnManager = Get.find<DeviceSnManager>();
    final deviceSn = deviceSnManager.getDeviceSn();

    if (deviceSn.isEmpty) {
      developer.log('⚠️ 设备SN为空，无法获取心率变异性数据', name: 'HRVController');
      return;
    }

    // 调用心率变异性平均值接口
    _fetchHrvAverage(deviceSn, recordDate);
  }
}
